package com.telecom.at.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.telecom.at.db.dac.Dac;
import com.telecom.at.db.model.AvgFlow;
import com.telecom.at.db.model.BWList;
import com.telecom.at.db.model.User;

@WebServlet("/json/JsonAvgFlow")
public class JsonAvgFlow extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int date = Integer.parseInt(request.getParameter("date"));
        double avgFlow = Integer.parseInt(request.getParameter("avgFlow"));
        int days = Integer.parseInt(request.getParameter("days"));
        //System.out.println(date);
        //System.out.println(avgFlow);
        //System.out.println(days);
        int startDate = date * 10000 + 100;
        int endDate = date * 10000 + 10100;
        // startDate = 2017070100;
        // endDate = 2017080100;

        List<AvgFlow> flowList = null;
        User curUser = (User) request.getSession().getAttribute("curUser");
        if (curUser.getId() == 0) {
            flowList = Dac.getInstance().getAvgFlowByAvgFlowDaysDate(startDate, endDate,avgFlow,days);
        } else {
            flowList = Dac.getInstance().getAvgFlowByAvgFlowDaysCityDate(startDate, endDate, curUser.getCity(),avgFlow,days);
        }
        List<BWList>  bWList =Dac.getInstance().allBWList();
        Set<String> accountList=new HashSet<String>();
	       for(BWList bWList2:bWList)
	    	   accountList.add(bWList2.getAccount());
        List<AvgFlow> flowList2 =new ArrayList<AvgFlow>();
        for(AvgFlow avgFlow2:flowList) {
			if(!accountList.contains(avgFlow2.getAccount())) {
				
				flowList2.add(avgFlow2);
			}
		}

        JSONArray jsonArray = new JSONArray(flowList2);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", flowList.size());
        jsonObject.put("subjects", jsonArray);
        // System.out.println(jsonArray);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // System.out.println(jsonObject.toString());
        response.getWriter().write(jsonObject.toString());
    }
}
